from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.generics import ListCreateAPIView
from django.core.paginator import Paginator
from .models import User, Role, Permission, Menu
from .serializers import (
    PermissionSerializer, RoleSerializer,
    MenuSerializer, UserManagementSerializer
)
from common.response import APIResponse


# 权限管理视图
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def permission_list(request):
    """权限列表和创建"""
    if request.method == 'GET':
        permissions = Permission.objects.all().order_by('id')

        # 分页
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        paginator = Paginator(permissions, page_size)
        page_obj = paginator.get_page(page)

        serializer = PermissionSerializer(page_obj, many=True)
        return Response({
            'success': True,
            'data': {
                'results': serializer.data,
                'total': paginator.count,
                'page': int(page),
                'page_size': int(page_size),
                'total_pages': paginator.num_pages
            }
        })

    elif request.method == 'POST':
        serializer = PermissionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '权限创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)

        return Response({
            'success': False,
            'message': '权限创建失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def permission_detail(request, pk):
    """权限详情、更新和删除"""
    try:
        permission = Permission.objects.get(pk=pk)
    except Permission.DoesNotExist:
        return Response({
            'success': False,
            'message': '权限不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = PermissionSerializer(permission)
        return Response({
            'success': True,
            'data': serializer.data
        })

    elif request.method == 'PUT':
        serializer = PermissionSerializer(permission, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '权限更新成功',
                'data': serializer.data
            })

        return Response({
            'success': False,
            'message': '权限更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        permission.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# 角色管理视图
from rest_framework.generics import ListCreateAPIView
from common.pagination import StandardResultsSetPagination

class RoleListCreateView(ListCreateAPIView):
    """角色列表和创建"""
    queryset = Role.objects.all().order_by('id')
    serializer_class = RoleSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.GET.get('name', '').strip()
        if name:
            queryset = queryset.filter(name__icontains=name)
        return queryset

# 保持向后兼容的函数视图
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def role_list(request):
    """角色列表和创建 - 兼容性视图"""
    if request.method == 'GET':
        roles = Role.objects.all().order_by('id')

        # 搜索过滤
        name = request.GET.get('name', '').strip()
        if name:
            roles = roles.filter(name__icontains=name)

        # 使用DRF的分页器
        from common.pagination import StandardResultsSetPagination
        paginator = StandardResultsSetPagination()
        page = paginator.paginate_queryset(roles, request)
        if page is not None:
            serializer = RoleSerializer(page, many=True)
            return paginator.get_paginated_response(serializer.data)

        # 如果没有分页，直接返回所有数据
        serializer = RoleSerializer(roles, many=True)
        return Response({
            'success': True,
            'data': {
                'results': serializer.data,
                'total': roles.count()
            }
        })

    elif request.method == 'POST':
        serializer = RoleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '角色创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)

        return Response({
            'success': False,
            'message': '角色创建失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def role_detail(request, pk):
    """角色详情、更新和删除"""
    try:
        role = Role.objects.get(pk=pk)
    except Role.DoesNotExist:
        return Response({
            'success': False,
            'message': '角色不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = RoleSerializer(role)
        return Response({
            'success': True,
            'data': serializer.data
        })

    elif request.method == 'PUT':
        serializer = RoleSerializer(role, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '角色更新成功',
                'data': serializer.data
            })

        return Response({
            'success': False,
            'message': '角色更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        role.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# 用户管理视图
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_list(request):
    """用户列表"""
    users = User.objects.all().order_by('id')

    # 分页
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    paginator = Paginator(users, page_size)
    page_obj = paginator.get_page(page)

    serializer = UserManagementSerializer(page_obj, many=True)
    return Response({
        'success': True,
        'data': {
            'results': serializer.data,
            'total': paginator.count,
            'page': int(page),
            'page_size': int(page_size),
            'total_pages': paginator.num_pages
        }
    })


@api_view(['GET', 'PUT'])
@permission_classes([IsAuthenticated])
def user_detail(request, pk):
    """用户详情和更新"""
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserManagementSerializer(user)
        return Response({
            'success': True,
            'data': serializer.data
        })

    elif request.method == 'PUT':
        serializer = UserManagementSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '用户更新成功',
                'data': serializer.data
            })

        return Response({
            'success': False,
            'message': '用户更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


# 菜单管理视图
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def menu_list(request):
    """菜单列表和创建"""
    if request.method == 'GET':
        # 获取所有菜单，按层级和排序显示
        all_menus = Menu.objects.filter(is_active=True).order_by('sort_order')

        # 构建树形结构数据
        menu_data = []
        for menu in all_menus:
            menu_dict = {
                'id': menu.id,
                'name': menu.name,
                'path': menu.path,
                'component': menu.component,
                'icon': menu.icon,
                'parent_id': menu.parent.id if menu.parent else None,
                'parent_name': menu.parent.name if menu.parent else None,
                'sort_order': menu.sort_order,
                'is_active': menu.is_active,
                'created_at': menu.created_at,
                'updated_at': menu.updated_at
            }
            menu_data.append(menu_dict)

        return Response({
            'success': True,
            'data': menu_data
        })

    elif request.method == 'POST':
        serializer = MenuSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '菜单创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)

        return Response({
            'success': False,
            'message': '菜单创建失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def menu_detail(request, pk):
    """菜单详情、更新和删除"""
    try:
        menu = Menu.objects.get(pk=pk)
    except Menu.DoesNotExist:
        return Response({
            'success': False,
            'message': '菜单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = MenuSerializer(menu)
        return Response({
            'success': True,
            'data': serializer.data
        })

    elif request.method == 'PUT':
        serializer = MenuSerializer(menu, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '菜单更新成功',
                'data': serializer.data
            })

        return Response({
            'success': False,
            'message': '菜单更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        menu.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_menus(request):
    """获取当前用户可访问的菜单"""
    user = request.user

    # 获取用户的所有权限
    user_permissions = Permission.objects.filter(
        role__userrole__user=user
    ).distinct()

    # 获取用户可访问的菜单
    accessible_menus = Menu.objects.filter(
        permissions__in=user_permissions,
        is_active=True,
        parent=None
    ).distinct().order_by('sort_order')

    serializer = MenuSerializer(accessible_menus, many=True)
    return Response({
        'success': True,
        'data': serializer.data
    })
